<?php

namespace app\controller\api;

use app\core\ApiController;
use app\service\GoodsService;
use app\service\IncomeService;
use app\service\MemberService;
use app\service\OrderService;
use app\model\Order;
use \app\model\Member;
use app\service\TeamIncomeService;

class Goods extends ApiController
{

    /**
     *认购商品列表
     */
    public function list()
    {
        $page = input('post.page', 1);
        $limit = input('post.limit', 10);
        $searchQuery = input('post.searchQuery', null);
        $data = GoodsService::invoke()->list($page, $limit, $searchQuery);
        $this->response->success($data);
    }

    /**
     *认购商品收益-定时任务
     */
    public function incomeTask()
    {
        $rs = false;
        $count = (new Order())->where(['status' => 2])->count();
        $limit = 10;
        $num = ceil($count / $limit);
        for ($i = 1; $i <= $num; $i++) {
            $page = $i;
            $searchQuery = input('post.searchQuery', null);
            $data = OrderService::invoke()->list($page, $limit, $searchQuery);
            foreach ($data['list'] as $map) {
                $rs = IncomeService::invoke()->addIncome($map, $map['member_info'], 3);
            }
        }
        $this->response->success($rs);
    }

    /**
     *认购团队分红-定时任务
     */
    public function teamTask()
    {
        $count = (new Member())->where(['is_agent' => 1])->count();
        $limit = 10;
        $num = ceil($count / $limit);
        $rs = false;
        for ($i = 1; $i <= $num; $i++) {
            $page = $i;
            $searchQuery = input('post.searchQuery', null);
            $searchQuery['is_agent'] = 1;
            $data = MemberService::invoke()->list($page, $limit, $searchQuery);
            foreach ($data['list'] as $map) {
                $amount = MemberService::invoke()->getSubMemberAmount($map['member_id']);
                if ($amount > 0) {
                    $rs = TeamIncomeService::invoke()->addTeamIncome($amount, $map, 1);
                }
            }
        }
        $this->response->success($rs);

    }

}